﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Cemit.PolyServer.Lobby
{
    /// <summary>
    /// 匹配倒计时，等待玩家返回匹配确认，在所有玩家完成确认后让所有玩家加入游戏房间，
    /// 在倒计时结束后发送匹配解散
    /// </summary>
    class MatchCountdown
    {
        public event Action OnAllPlayerConfirmed;
        public event Action OnTimeout;

        private Dictionary<string, bool> m_PlayerConfirmPairs = new Dictionary<string, bool>();

        private int confirmCount = 0;
        private int time;
        private bool isTimeout = false;

        /// <summary>
        /// 新建一个倒计时
        /// </summary>
        public MatchCountdown(Match match, int time)
        {
            foreach (var item in match.Players)
            {
                m_PlayerConfirmPairs.Add(item.ID, false);
            }

            this.time = time;
        }

        public void Start()
        {
            TimeCountdown(time);
        }

        async private void TimeCountdown(int time)
        {
            await Task.Delay(time * 1000);

            if (confirmCount != m_PlayerConfirmPairs.Count)
            {
                isTimeout = true;
                OnTimeout?.Invoke();
            }
        }

        public MatchCountdown Confirm(Player player)
        {
            if (isTimeout)
            {
                return this;
            }

            if (!m_PlayerConfirmPairs.ContainsKey(player.ID))
            {
                this.LogWarning("确认匹配失败！玩家不在该匹配队列中！");
                return this;
            }

            if (m_PlayerConfirmPairs[player.ID])
            {
                this.LogWarning("确认匹配失败！该玩家已经确认！");
                return this;
            }

            lock (m_PlayerConfirmPairs)
            {
                m_PlayerConfirmPairs[player.ID] = true;
                confirmCount++;
            }

            if (confirmCount == m_PlayerConfirmPairs.Count)
            {
                OnAllPlayerConfirmed?.Invoke();
            }

            return this;
        }
    }
}
